﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Jzy.Core.Utility;

namespace Forum.Web.BaseCode
{
    public class LoginInfo
    {     
        private const string TOKEN = "Token";
        private const string MEMBER_INFO = "MemberInfo";

        private string _token;

        private string _currentUserHostAddress; //当前用户的IP地址

        public LoginInfo()
        {
            HttpCookie token = System.Web.HttpContext.Current.Request.Cookies[TOKEN];
            HttpCookie memberInfo = System.Web.HttpContext.Current.Request.Cookies[MEMBER_INFO];
            _currentUserHostAddress  = System.Web.HttpContext.Current.Request.UserHostAddress;

            string cookieUserHostAddress = null;//cookie里记录的IP地址


            if (memberInfo != null)
            {
                string strMember = StrUtil.DecryptDES(memberInfo.Value);
                string[] tmps = strMember.Split(';');
                this.MemberID = int.Parse(tmps[0]);
                this.MemberLoginName = tmps[1];
                this.Expires = DateTime.Parse(tmps[2]);

                cookieUserHostAddress = tmps[3];
            }


            if (token != null)
            {
                _token = StrUtil.DecryptDES(token.Value);
            }
            else
            {
                if (this.Expires > DateTime.Now && _currentUserHostAddress == cookieUserHostAddress)
                {
                    _token = _currentUserHostAddress;
                }
            }

                       

        }


        public string MemberLoginName
        {
            get;
            set;
        }

        public int MemberID
        {
            get;
            set;
        }

        public DateTime Expires
        {
            get;
            set;
        }

        public void Save()
        {
            HttpCookie token = System.Web.HttpContext.Current.Request.Cookies[TOKEN];
            token.Value = StrUtil.EncryptDES(_currentUserHostAddress);

            HttpCookie memberInfo = System.Web.HttpContext.Current.Request.Cookies[MEMBER_INFO];
            memberInfo.Expires = DateTime.MaxValue;
            string strMemberInfo = this.MemberID + ";" + this.MemberLoginName + ";" + this.Expires + ";" + _currentUserHostAddress;
            memberInfo.Value = StrUtil.EncryptDES(strMemberInfo);

            System.Web.HttpContext.Current.Response.Cookies.Add(token);
            System.Web.HttpContext.Current.Response.Cookies.Add(memberInfo);


        }

        public bool IsLogin
        {
            get
            {
                return _token == _currentUserHostAddress;
            }
        }
    }
}